

import Base from './base.js';

const path = require('path');

function isEmpty(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}
const appid = 'wxf54dea83d4b4ba11';
const secret = '253c4572f948125d547624e1e89e958e';
const request = require('request');
const fs = require('fs');

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    const uid = this.get('id');
    const user_model = this.model('user');
    const userinfo = await user_model.where(`id="${uid}"`).find();
    const model = this.model('product');
    let data;
    if (userinfo.ispmo) {
      data = await model.where('is_show!=0').order('createtime DESC').select();
    } else {
      const product_user = this.model();
      data = await product_user.query(`select a.id,a.teamleader,a.title,a.id,a.owner,a.productdate,a.status,a.createtime,user.name from (select product.title,product.teamleader,product.id,product.owner,product.productdate,product.status,product.createtime from product left join product_user on product.id=product_user.pid where product_user.userid = ${uid} and product.is_show!=0  order by product.createtime desc) as a left join user on  a.owner=user.id`);
      //data = await product_user.where('userid="'+uid+'"').select();
      //data = data.map((item)=>{return item.productlist})
    }

    //data.forEach()
    //data.owner2 = await this.getOwner(data.owner)
    this.success(data);
  }

  //获取项目信息
  async getinfoAction() {
    const pid = this.get('pid');
    if (!pid) {
      this.error('项目页不存在');
      return false;
    }
    const model = this.model('product');
    const data = await model.where(`id="${pid}"`).find();
    this.success(data);
  }

  //获取指定项目的信息+组别
  async getinfowithteamlistAction() {
    const pid = this.get('pid');
    if (!pid) {
      this.error('项目页不存在');
      return false;
    }
    const model = this.model('product');
    const data = await model.where(`id="${pid}"`).find();
    const teamlist = this.model('teams');

    const teamsdata = await teamlist.select();
    const result = { data, teamlist: teamsdata };
    this.success(result);
  }

  //获取指定项目的信息+组别
  async getworktypelistAction() {
    const model = this.model('category');
    const data = await model.select();
    const result = data;
    this.success(result);
  }

  async createdailyAction() {
    const formdata = this.post();
    const uid = formdata.uid;
    if (!uid) {
      this.error('用户不存在');
      return false;
    }
    const model = this.model('user');
    const userinfo = await model.where(`id=${uid}`).find();
    if (!userinfo) {
      this.error('用户不存在');
      return false;
    }
    const daily = this.model('daily');

    await daily.add(formdata.data);
    this.success('提交成功');
  }

  async getqrcodeAction() {
    //   fs.open('./static/img/getqrcode.jpeg', 'wx', (err, fd) => {
    //   if (err) {
    //     throw err;
    //   }
    // });
    const path2 = path.resolve(__dirname, '../../../www/static/img');

    const self = this;
    const pid = this.get('pid');
    let openid;
    const that = this;
    const filename = `getqrcode_${pid}`;
    const model = this.model('product');
    const data = await model.where(`id="${pid}"`).find();
    const l = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&&appid=${appid}&secret=${secret}`;
    request(l, (error, response, body) => {
      const json = JSON.parse(body);
      const access_token = json.access_token;
      const l2 = `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${access_token}`;
      request.post({
        url: l2,
        body: JSON.stringify({ path: `pages/index/join/join?pid=${pid}`, width: 430 }),
        headers: {
          'content-type': 'application/json',
        },
        success() {
          console.log(222);
        },
      }).pipe(fs.createWriteStream(`${path2}/${filename}.jpeg`)).on('finish', () => {
        console.log(222);
        that.success({ url: `https://xhhfe.xinhehui.com/static/img/${filename}.jpeg`, product: data });
      });
    });
  }
}
